package com.moss.cloud.auth.biz.listener;

import com.moss.cloud.auth.biz.events.LoginEvent;
import com.moss.cloud.auth.biz.service.ISysMenuService;
import com.moss.cloud.auth.biz.service.ISysUserService;
import com.moss.cloud.auth.biz.utils.UserAgentUtil;
import com.moss.cloud.common.base.model.po.SysUser;
import com.moss.cloud.common.core.constant.Constant;
import com.moss.cloud.common.core.model.dto.UserLoginDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 瑾年
 * @data 2019/08/11 7:24
 * 授权成功处理事件  监听器
 */
@Component
@Slf4j
public class AuthorizationSuccessListener implements ApplicationListener<AuthenticationSuccessEvent> {

    private final HttpServletRequest request;
    private final ISysMenuService sysMenuService;
    private final LoginEvent loginEvent;
    private final ISysUserService sysUserService;

    public AuthorizationSuccessListener(HttpServletRequest request, ISysMenuService sysMenuService, LoginEvent loginEvent, ISysUserService sysUserService) {
        this.request = request;
        this.sysMenuService = sysMenuService;
        this.loginEvent = loginEvent;
        this.sysUserService = sysUserService;
    }

    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {
        if (!event.getAuthentication().getName().equals(Constant.DEF_CLIENT)) {
            log.info("授权成功的处理方案-当前授权的用户名称:{}", event.getAuthentication().getName());
            SysUser sysUser = sysUserService.getUserByUsername(event.getAuthentication().getName());
            UserLoginDTO dto = UserAgentUtil.getSuccess(request, Constant.LOGIN_SUCCESS, event, sysUser);
            // 授权成功初始化用户角色资源信息
            sysMenuService.queryByUsername(event.getAuthentication().getName());
            // 授权成功消息通知 1.登录日志消息或者同步下游服务数据消息
            // 2.发送登录成功的邮件或者短信提示消息
            loginEvent.sendUserLoginEvent(dto);
            // 缓存当前登录用户信息
            sysUserService.cacheUserInfo(event.getAuthentication().getName());
        }
    }
}
